/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cw.controller;

import cw.controller.exceptions.IllegalOrphanException;
import cw.controller.exceptions.NonexistentEntityException;
import cw.controller.exceptions.PreexistingEntityException;
import cw.entity.Level;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import cw.entity.Puzzle;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 *
 * @author VinhTC
 */
public class LevelJpaController {

    public LevelJpaController() {
        emf = Persistence.createEntityManagerFactory("CrossWordsAdminPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Level level) throws PreexistingEntityException, Exception {
        if (level.getPuzzleList() == null) {
            level.setPuzzleList(new ArrayList<Puzzle>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Puzzle> attachedPuzzleList = new ArrayList<Puzzle>();
            for (Puzzle puzzleListPuzzleToAttach : level.getPuzzleList()) {
                puzzleListPuzzleToAttach = em.getReference(puzzleListPuzzleToAttach.getClass(), puzzleListPuzzleToAttach.getPuzzleId());
                attachedPuzzleList.add(puzzleListPuzzleToAttach);
            }
            level.setPuzzleList(attachedPuzzleList);
            em.persist(level);
            for (Puzzle puzzleListPuzzle : level.getPuzzleList()) {
                Level oldLevelOfPuzzleListPuzzle = puzzleListPuzzle.getLevel();
                puzzleListPuzzle.setLevel(level);
                puzzleListPuzzle = em.merge(puzzleListPuzzle);
                if (oldLevelOfPuzzleListPuzzle != null) {
                    oldLevelOfPuzzleListPuzzle.getPuzzleList().remove(puzzleListPuzzle);
                    oldLevelOfPuzzleListPuzzle = em.merge(oldLevelOfPuzzleListPuzzle);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findLevel(level.getLevelId()) != null) {
                throw new PreexistingEntityException("Level " + level + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Level level) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Level persistentLevel = em.find(Level.class, level.getLevelId());
            List<Puzzle> puzzleListOld = persistentLevel.getPuzzleList();
            List<Puzzle> puzzleListNew = level.getPuzzleList();
            List<String> illegalOrphanMessages = null;
            for (Puzzle puzzleListOldPuzzle : puzzleListOld) {
                if (!puzzleListNew.contains(puzzleListOldPuzzle)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Puzzle " + puzzleListOldPuzzle + " since its level field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Puzzle> attachedPuzzleListNew = new ArrayList<Puzzle>();
            for (Puzzle puzzleListNewPuzzleToAttach : puzzleListNew) {
                puzzleListNewPuzzleToAttach = em.getReference(puzzleListNewPuzzleToAttach.getClass(), puzzleListNewPuzzleToAttach.getPuzzleId());
                attachedPuzzleListNew.add(puzzleListNewPuzzleToAttach);
            }
            puzzleListNew = attachedPuzzleListNew;
            level.setPuzzleList(puzzleListNew);
            level = em.merge(level);
            for (Puzzle puzzleListNewPuzzle : puzzleListNew) {
                if (!puzzleListOld.contains(puzzleListNewPuzzle)) {
                    Level oldLevelOfPuzzleListNewPuzzle = puzzleListNewPuzzle.getLevel();
                    puzzleListNewPuzzle.setLevel(level);
                    puzzleListNewPuzzle = em.merge(puzzleListNewPuzzle);
                    if (oldLevelOfPuzzleListNewPuzzle != null && !oldLevelOfPuzzleListNewPuzzle.equals(level)) {
                        oldLevelOfPuzzleListNewPuzzle.getPuzzleList().remove(puzzleListNewPuzzle);
                        oldLevelOfPuzzleListNewPuzzle = em.merge(oldLevelOfPuzzleListNewPuzzle);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = level.getLevelId();
                if (findLevel(id) == null) {
                    throw new NonexistentEntityException("The level with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Level level;
            try {
                level = em.getReference(Level.class, id);
                level.getLevelId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The level with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Puzzle> puzzleListOrphanCheck = level.getPuzzleList();
            for (Puzzle puzzleListOrphanCheckPuzzle : puzzleListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Level (" + level + ") cannot be destroyed since the Puzzle " + puzzleListOrphanCheckPuzzle + " in its puzzleList field has a non-nullable level field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(level);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Level> findLevelEntities() {
        return findLevelEntities(true, -1, -1);
    }

    public List<Level> findLevelEntities(int maxResults, int firstResult) {
        return findLevelEntities(false, maxResults, firstResult);
    }

    private List<Level> findLevelEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Level.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Level findLevel(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Level.class, id);
        } finally {
            em.close();
        }
    }

    public int getLevelCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Level> rt = cq.from(Level.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    /**
     * getLevelByName
     * @param levelName
     * @return Level
     */
    public Level getLevelByName(String levelName) {
        Level level = null;
        try {
            Query query = getEntityManager().createNamedQuery("Level.findByLevelName");
            query.setParameter("levelName", levelName);

            level = (Level) query.getSingleResult();
        } catch (Exception e) {
            while (level == null) {
                Query query = getEntityManager().createNamedQuery("Level.findByLevelName");
                query.setParameter("levelName", levelName);

                level = (Level) query.getSingleResult();
            }
            Logger.getLogger(LevelJpaController.class.getName()).log(java.util.logging.Level.SEVERE, null, e);
        }
        return level;
    }
}
